var lsInfo = {
  current: 1,
  pageSize: allPageSize,
  data: [],
  data1: [],
  totalRow: 0,
  totalPage: 0,
  oneDate: {},
  editState: false,
  calendar: []
};

// document.getElementById('nav').innerHTML = template('navs', navinfo3);
$('#nav li').eq(0).addClass('active');

/*var add = true;
var projectId = getUrlId();*/
var add = true;
var projectId = getUrlId().id;
var start = getUrlId().start.split('#').join(' ');
var end = getUrlId().end.split('#').join(' ');
function getUrlId() {
  var url = window.location.href;
  url = url.slice(url.lastIndexOf('/') + 1).split('#-#');
  return {
    id: url[0],
    start: url[1],
    end: url[2]
  }
}

var getList = function () {};
var getList1 = function () {};

$('#calendar').fullCalendar({
  header: {
    left: 'today prev,next',
    center: 'title',
    right: ''
  },
  handleWindowResize: false,
  eventLimit: true,
  monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
  monthNamesShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
  dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
  dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
  today: ["今天"],
  firstDay: 1,
  titleFormat: 'YYYY年MM月',
  buttonText: {
    today: '本月',
    month: '月',
    week: '周',
    day: '日',
    prev: '上一月',
    next: '下一月'
  },
  loading: function (bool) {
    if (bool) {
      console.log('loading');
    } else {
      console.log('complete');
    }
  },
  dayClick: function (date, jsEvent, view) {//日期点击后弹出的jq ui的框，添加日程记录

  },
  eventClick: function (calEvent, jsEvent, view) {
    // var index = parseInt(calEvent.content, 10);
    add = false;
    lsInfo.oneDate = lsInfo.calendar[calEvent.content];
    var v = lsInfo.oneDate;
    assign(v);

  },
  eventAfterRender: function (event, element, view) {
  },
  events: function (start, end, timezone, callback) {
    var d = new Date(end);
    var year = d.getFullYear();
    var month = d.getMonth();
    var day = '01';
    if (month === 0) {
      year = year - 1;
      month = 12;
    }
    var date = year + '-' + month + '-' + day + ' 00:00';
    // console.log(date);
    getList1 = function (obj) {
      // 根据地址栏获取id

      $.ajax({
        cache: false,
        async: false,
        url: '/api/CommonApi?API=GetProjectSchedulesByDate',
        type: 'get',
        data: {
          ProjectID: projectId,
          Date: date
        },
        dataType: 'json',
        success: function (data) {
          // console.log(data)
          if (data.Success) {
            obj.callback(data);
          }
        }
      });
    };
    getList1({
      size: lsInfo.pageSize,
      index: lsInfo.current,
      callback: function (data) {
        // console.log(data)
        // console.log(JSON.stringify(data));
        var newData = data.ApiParamObj;
        setCalendarData(newData);

        // 列表数据
        // document.getElementById('tableList').innerHTML = template('list', newData);
        // // 分页
        // var pagesInfo = data.ApiParamObj;
        lsInfo.data1 = newData;
        // lsInfo.totalRow = pagesInfo[0].totalRow;
        // lsInfo.totalPage = pagesInfo[0].totalPage;
        // $('#totalRow').html(lsInfo.totalRow);
        // pagesSet(lsInfo);
        // setPageSize(lsInfo);
        loading.hide();
      }
    });
  }
});

getList = function (obj) {

  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=GetProjectSchedules',
    type: 'get',
    data: {
      ProjectID: projectId,
      sorts: ' CreateTime DESC',
      pagesize: lsInfo.pageSize,
      page: lsInfo.current
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      if (data.Success) {
        obj.callback(data);
      }
    }
  });
};
getList({
  size: lsInfo.pageSize,
  index: lsInfo.current,
  callback: function (data) {
    // console.log(data)
    // console.log(JSON.stringify(data));
    var newData = data.ApiParamObj;
    // setCalendarData(newData);
    for (var key in newData[0]) {
      newData[0][key].StartTime = new Date(newData[0][key].StartTime).pattern('yyyy/MM/dd');
      newData[0][key].EndTime = new Date(newData[0][key].EndTime).pattern('yyyy/MM/dd');
    }
    // 列表数据
    document.getElementById('tableList').innerHTML = template('list', newData[0]);
    // 分页
    var pagesInfo = data.ApiParamObj[1];
    lsInfo.data = newData;
    lsInfo.totalRow = pagesInfo[0].totalRow;
    lsInfo.totalPage = pagesInfo[0].totalPage;
    $('#totalRow').html(lsInfo.totalRow);
    pagesSet(lsInfo);
    setPageSize(lsInfo);
    loading.hide();
  }
});

// 获取项目人员
getProjectUser();
function getProjectUser() {
  $.ajax({
    url: '/api/CommonApi?API=PM_RUN_GetProjectUsers',
    type: 'get',
    data: {
      ProjectID: projectId
    },
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        // console.log(data)
        // console.log(JSON.stringify(data));
        var obj = {};
        var list = data.ApiParamObj;
        var i = 0;
        var l = list.length;

        for (; i < l; i++) {
          // console.log(list[i])
          if (!obj[list[i].RoleType]) {
            obj[list[i].RoleType] = [];
          }
          // if (list[i].IsAllot === '已分配') {
          obj[list[i].RoleType].push(list[i].UserName);
          // }
        }
        // console.log(obj)

        var h = '';

        var showKey = [
          '项目经理',
          '项目执行',
          '项目人员'
        ];

        var hArr = [
          obj['PM'],
          obj['RUN'],
          obj['PP']
        ];

        for (i = 0, l = hArr.length;i < l;i++) {
          h += '<p><span>' + showKey[i] + '：</span>' + hArr[i].join(', ') + '</p>';
        }

       /* var showKey = {
          PM: '项目经理',
          PP: '项目人员',
          RUN: '项目执行'
        };
        for (var key in obj) {
          h += '<p><span>' + showKey[key] + '：</span>' + obj[key].join(', ') + '</p>';
        }*/

        document.getElementById('projectInfo').innerHTML = h;
      }
    }
  });
}

// 点击分页请求事件
var showPage = function (o) {
  // console.log(o)
  getList({
    size: o.pageSize,
    index: o.current,
    callback: function (data) {
      // console.log(data)
      // console.log(JSON.stringify(data));
      var newData = data.ApiParamObj;
      // for (var key in newData) {
      //   if (newData[key]['State'] === '????') {
      //     newData[key]['State'] = '';
      //   }
      // }
      for (var key in newData[0]) {
        newData[0][key].StartTime = new Date(newData[0][key].StartTime).pattern('yyyy/MM/dd');
        newData[0][key].EndTime = new Date(newData[0][key].EndTime).pattern('yyyy/MM/dd');
      }
      // setCalendarData(newData);
      // 列表数据
      document.getElementById('tableList').innerHTML = template('list', newData[0]);
      // 分页
      var pagesInfo = data.ApiParamObj[1];
      o.data = newData;
      o.totalRow = pagesInfo[0].totalRow;
      o.totalPage = pagesInfo[0].totalPage;

      $('#totalRow').html(o.totalRow);
      pagesSet(o);
      loading.hide();
    }
  });
};

// 渲染日历数据
function setCalendarData(data) {
  // console.log(data)
  // var i = 0;
  lsInfo.calendar = data;
  $("#calendar").fullCalendar('removeEvents');
  for (var key in data) {
    // console.log(data[key])
    // lsInfo.calendar.push({
    //   id: data[key].Name.ID,
    //   title: data[key].Name,
    //   start: moment(new Date(data[key].StartTime).pattern('yyyy-MM-dd 00:00')).format(),
    //   end: moment(new Date(data[key].EndTime).pattern('yyyy-MM-dd 24:00')).format()
    // });
    $("#calendar").fullCalendar('renderEvent', {
      id: data[key].Name.ID,
      title: data[key].Name,
      start: moment(new Date(data[key].StartTime).pattern('yyyy-MM-dd 00:00')).format(),
      end: moment(new Date(data[key].EndTime).pattern('yyyy-MM-dd 24:00')).format(),
      content: key
    }, false);
    // i++;
  }
}

var b1 = new Vue({
  el: '#tLists',
  data: {
    table: [{
      startTime: '',
      endTime: '',
      teacher: '',
      tDays: '',
      eDays: ''
    }],
    teacher: [],
    allData: []
  },
  methods: {
    /*change: function (c, d) {
     console.log(c, d)
     },*/
    del: function ($index) {
      var data = b1.allData[$index];
      console.log(data);
      $.ajax({
        url: '/api/CommonApi?API=TeacherScheduleSettingTableOp',
        type: 'post',
        data: {
          ApiParamObj: JSON.stringify({
            ID: data.ID,
            IsDelete: 1
          })
        },
        dataType: 'json',
        success: function (data) {
          if (data.Success) {
            // console.log(data);

            b1.allData.splice($index, 1);
          }
        }
      });
    },
    add: function () {
      var arr = [];
      var o = {};
      var ids = [];
      for (var key in b1.table[0].teacher) {
        arr.push(b1.table[0].teacher[key].name);
        ids.push(b1.table[0].teacher[key].id);
      }
      b1.table[0].teacher = arr.join(', ');
      for (var key in b1.table[0]) {
        o[key] = b1.table[0][key];
      }
      o.id = ids.join(', ');
      // console.log(ids);

      // 项目执行开始
      var st = lsInfo.oneDate.StartTime;
      // 项目执行结束
      var et = lsInfo.oneDate.EndTime;


      var v1 = $('#td4').val();
      var v2 = $('#td5').val();
      var v3 = o.id;
      var v4 = $('#td7').val();
      var v5 = $('#td8').val();

      // console.log(new Date(v1) > new Date(st))
      // console.log(Date.parse(v1))
      // console.log(Date.parse(st))
      // console.log(st > Date.parse(v1))
      // console.log(v1, v2, v3, v4, v5)

      var validator = new Validator();
      validator.add(v1, [{
        strategy: 'isNonEmpty',
        errorMsg: '时间开始不能为空'
      }]);

      validator.add(v2, [{
        strategy: 'isNonEmpty',
        errorMsg: '时间结束不能为空'
      }]);

      validator.add(v3, [{
        strategy: 'isNonEmpty',
        errorMsg: '老师不能为空'
      }]);

      validator.add(v4, [{
        strategy: 'isNonEmpty',
        errorMsg: '差旅天数不能为空'
      }, {
        strategy: 'isNumber',
        errorMsg: '差旅天数必须为数字'
      }]);

      validator.add(v5, [{
        strategy: 'isNonEmpty',
        errorMsg: '执行天数不能为空'
      }, {
        strategy: 'isNumber',
        errorMsg: '执行天数必须为数字'
      }]);

      var errmsg = validator.start();
      if (errmsg) {
        alert(errmsg);
        return false;
      }

      var submitObj = {
        ProjectID: projectId,
        ProjectScheduleID: lsInfo.oneDate.ID,
        TeacherID: o.id,
        ExecutionStartDate: o.startTime,
        ExecutionEndDate: o.endTime,
        TravelDays: o.tDays,
        ExecutionDays: o.eDays
      };
      console.log(submitObj)

      $.ajax({
        url: '/api/CommonApi?API=TeacherScheduleSettingTableOp',
        type: 'put',
        data: {
          ApiParamObj: JSON.stringify(submitObj)
        },
        dataType: 'json',
        success: function (data) {
          if (data.Success) {
            // console.log(data);
            b1.allData.push(o);

            b1.table = [{
              startTime: '',
              endTime: '',
              teacher: '',
              tDays: '',
              eDays: ''
            }];


            setTimeout(function () {
              select2Change();
              datetimepicker();
            }, 0);
          }
        }
      });
    }
  }
});
select2Change();
function select2Change() {
  var i = 0;
  var o = $('#tLists select');
  var l = o.length;
  for (; i < l; i++) {
    // console.log(o[i])
    $(o[i]).select2();
    (function (i) {
      $(o[i]).on('select2:unselect', function () {
        console.log('unselect');
        var arr = [];
        $(this).find(':selected').each(function () {
          arr.push({
            id: $(this).val(),
            name: trim($(this).html())
          });
        });
        Vue.set(b1.table[i], 'teacher', arr);
      });

      $(o[i]).on('select2:select', function (evt) {
        console.log('select');
        var arr = [];
        $(this).find(':selected').each(function () {
          arr.push({
            id: $(this).val(),
            name: trim($(this).html())
          });
        });
        Vue.set(b1.table[i], 'teacher', arr);
      });

      $(o[i]).on('select2:unselecting', function (evt) {
        console.log('unselecting');
        var arr = [];
        $(this).find(':selected').each(function () {
          arr.push({
            id: $(this).val(),
            name: trim($(this).html())
          });
        });
        Vue.set(b1.table[i], 'teacher', arr);
      });
    }(i))
  }


}

// 日历
/*$('.datepk').parent().addClass('date').end()
  .next().addClass('glyphicon glyphicon-th')
  .before('<span class="c-select-btn remove glyphicon glyphicon-remove"></span>');*/

function datetimepicker() {
  /*$('#tLists .date').datetimepicker({
    // bootcssVer: 3,
    todayBtn: true,
    weekStart: 0,
    autoclose: 1,
    // todayHighlight: 1,
    startView: 2,
    startDate: new Date(),
    format: 'yyyy-mm-dd',
    // forceParse: 1,
    // showMeridian: 1,
    language: 'zh-CN',
    minView: 2
  });*/
  var start = new Date(lsInfo.oneDate.StartTime).pattern('yyyy-MM-dd');
  var end = new Date(lsInfo.oneDate.EndTime).pattern('yyyy-MM-dd');

/*  $('.input-daterange input').datepicker({
    // bootcssVer: 3,
    todayBtn: 'linked',
    weekStart: 0,
    autoclose: true,
    // todayHighlight: 1,
    startView: 0,
    startDate: start,
    endDate: end,
    format: 'yyyy-mm-dd',
    // forceParse: 1,
    // showMeridian: 1,
    language: 'zh-CN',
    minView: 0
  });*/
  $('.input-daterange input').datetimepicker('remove');
  $('.input-daterange input').datetimepicker({
    bootcssVer: 2,
    todayBtn: true,
    weekStart: 0,
    autoclose: 1,
    startView: 2,
    startDate: start,
    endDate: end,
    format: 'yyyy-mm-dd',
    language: 'zh-CN',
    minView: 2
  });
}


$('#teacherManger .c-select-btn.remove.glyphicon-remove').on('click', function () {
  // console.log($(this).prev())
  $(this).parent().children('input[type="text"]').val('');
  return false;
});

// 讲师分配
$('#table').on('click', '.assign', function () {
  var index = $(this).parent().parent().index();
  lsInfo.oneDate = lsInfo.data[0][index];
  var v = lsInfo.oneDate;
  // console.log(v)
  assign(v);
});

function assign(v) {
  b1.allData = [];
  $('#td1').html(v.Name);
  var t = new Date(v.StartTime).pattern('yyyy年MM月dd日') + ' - ' + new Date(v.EndTime).pattern('yyyy年MM月dd日');
  $('#td3').html(t);

  datetimepicker();

  // 获取单条信息
  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=GetProjectSchedule',
    type: 'get',
    data: {
      'ProjectScheduleID': lsInfo.oneDate.ID
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      if (data.Success) {
        // 获取主题名称
        $('#td2').html(data.ApiParamObj[0].ProjectName);
      }

    }
  });
  // 获取项目老师
  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=GetProjectUserByTeacher',
    type: 'get',
    data: {
      'ProjectID': projectId
    },
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        // console.log(data)
        b1.teacher = data.ApiParamObj;
        getData();
      }

    }
  });
  // 项目运营-获取老师分配集合
  function getData() {
    $.ajax({
      cache: false,
      async: false,
      url: '/api/CommonApi?API=GetTeacherSchedules',
      type: 'get',
      data: {
        'ProjectScheduleID': lsInfo.oneDate.ID
      },
      dataType: 'json',
      success: function (data) {
        if (data.Success) {
          // console.log(data)
          var d = data.ApiParamObj;

          for (var key in d ) {
            d[key].ExecutionEndDate = new Date(d[key].ExecutionEndDate).pattern('yyyy/MM/dd');
            d[key].ExecutionStartDate = new Date(d[key].ExecutionStartDate).pattern('yyyy/MM/dd');
          }

          if (!d.length) {
            return;
          }
          var i = 0;
          var l = d.length;
          var arr = [];
          // b1.allData

          for (; i < l; i++) {
            // console.log(d[i]);
            var arr2 = [];
            (function (i) {
              var o = b1.teacher;
              var j = 0;
              var k = o.length;
              var arr1 = d[i].TeacherID.split(', ');
              // console.log(arr1)
              for (; j < k; j++) {
                if (arr1.indexOf(o[j].UserId) !== -1) {
                  arr2.push(o[j].UserName)
                }
              }
            }(i));

            arr.push({
              startTime: d[i].ExecutionStartDate,
              endTime: d[i].ExecutionEndDate,
              teacher: arr2.join(', '),
              tDays: d[i].TravelDays,
              eDays: d[i].ExecutionDays,
              ID: d[i].ID
            })
          }
          b1.allData = arr;
          b1.table[0].startTime = '';
          b1.table[0].endTime = '';
          b1.table[0].tDays = '';
          b1.table[0].eDays = '';
        }

      }
    });
  }

  $('#teacherManger').modal('show');
}

/*
// 保存
$('#btn-save').on('click', function () {
  var _this = $(this);
  var index = _this.parent().parent().index();
  lsInfo.oneDate = lsInfo.data[index];
  console.log(b1.table);
});*/
